<template>
  <div class="ms-list">
    <el-row class="operation">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">
          <icon name="home"></icon>
        </el-breadcrumb-item>
        <el-breadcrumb-item>服务</el-breadcrumb-item>
        <el-breadcrumb-item>首联反馈</el-breadcrumb-item>
        <el-breadcrumb-item>报表提交</el-breadcrumb-item>
      </el-breadcrumb>
      <el-button-group>
        <el-button type="primary" size="small" @click="addRow()">新增</el-button>
      </el-button-group>
    </el-row>

    <ms-slide
      :title="row.edit.enabled ? '编辑反馈' : '新增反馈'"
      :width="500"
      @close="closeSlideModify()"
      ref="slideModifyRow">
      <el-form class="form" label-width="120px" size="small" :model="row.form" ref="formModifyRow">
        <el-form-item
          label="日期选择"
          prop="day"
          :rules="[
              {required: true, message: '请选择日期'}
            ]">
          <el-date-picker
            :disabled="row.edit.enabled"
            v-model="row.form.day"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions"
            :value-format="row.format"
            size="mini">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-input v-model="row.form.province" placeholder="请填写省份"></el-input>
        </el-form-item>
        <el-form-item label="城市/地区" prop="city">
          <el-input v-model="row.form.city" placeholder="请填写城市"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile" :rules="[{required: true, message: '必填'}]">
          <el-input v-model="row.form.mobile" placeholder="请填写客户电话"></el-input>
        </el-form-item>
        <el-form-item label="QQ" prop="qq">
          <el-input v-model="row.form.qq" placeholder="请填写客户QQ"></el-input>
        </el-form-item>
        <el-form-item label="微信" prop="wechat">
          <el-input v-model="row.form.wechat" placeholder="请填写客户微信"></el-input>
        </el-form-item>
        <el-form-item label="意向" prop="intention" :rules="[{required: true, message: '必填'}]">
          <el-select v-model="row.form.intention" placeholder="请填写客户意向">
            <el-option label="A" :value="'A'"></el-option>
            <el-option label="B" :value="'B'"></el-option>
            <el-option label="C" :value="'C'"></el-option>
            <el-option label="D" :value="'D'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="沟通情况" prop="communication" :rules="[{required: true, message: '必填'}]">
          <el-input v-model="row.form.communication" placeholder="请填写与客户沟通的情况"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="row.form.remark" placeholder="请填写备注信息"></el-input>
        </el-form-item>
        <el-form-item label="来源" prop="resoure" :rules="[{required: true, message: '必填'}]">
          <el-select v-model="row.form.resoure" placeholder="请选择客户来源">
            <el-option label="百度搜索" :value="1"></el-option>
            <el-option label="今日头条" :value="2"></el-option>
            <el-option label="神马搜索" :value="3"></el-option>
            <el-option label="搜狗搜索" :value="4"></el-option>
            <el-option label="搜狗竞价" :value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关键字" prop="keyword" :rules="[{required: true, message: '必填'}]">
          <el-input v-model="row.form.keyword" placeholder="请填写关键字"></el-input>
        </el-form-item>
        <el-form-item label="首次接听状态" prop="firstAnswer" :rules="[{required: true, message: '必填'}]">
          <el-select v-model="row.form.firstAnswer" placeholder="请选择首次接听状态">
            <el-option label="接听" :value="0"></el-option>
            <el-option label="无人接听" :value="1"></el-option>
            <el-option label="拒接" :value="2"></el-option>
            <el-option label="空错号" :value="3"></el-option>
            <el-option label="无咨询" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工" prop="customerName" :rules="[{required: true, message: '必填'}]">
          <el-input v-model="row.form.customerName" placeholder="请填写员工姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitRow()">提交</el-button>
          <el-button v-if="!row.edit.enabled" @click="resetForm('formModifyRow')">重置</el-button>
        </el-form-item>
      </el-form>
    </ms-slide>

    <ms-search :data="search.list" @click="updateConditions"></ms-search>

    <el-table
      size="small" stripe border
      :max-height="tbHeight"
      :data="table.list"
      :fit="true">
      <el-table-column prop="day" label="日期" :formatter="dataFormat" min-width="90" fixed/>
      <el-table-column prop="name" label="客户姓名" min-width="100"/>
      <el-table-column prop="province" label="地址（省份+地区）" min-width="200">
        <template slot-scope="scope">
          {{scope.row.province}}{{scope.row.city}}
        </template>
      </el-table-column>
      <el-table-column prop="mobile" label="电话" min-width="150"/>
      <el-table-column prop="qq" label="QQ" min-width="100"/>
      <el-table-column prop="wechat" label="微信" min-width="100"/>
      <el-table-column prop="intention" label="意向" min-width="80"/>
      <el-table-column prop="remark" label="备注" min-width="100"/>
      <el-table-column prop="communication" label="沟通情况" min-width="150"/>
      <el-table-column prop="resoure" label="来源" min-width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.resoure === 1">百度搜索</span>
          <span v-else-if="scope.row.resoure === 2">今日头条</span>
          <span v-else-if="scope.row.resoure === 3">神马搜索</span>
          <span v-else-if="scope.row.resoure === 4">搜狗搜索</span>
          <span v-else-if="scope.row.resoure === 5">搜狗竞价</span>
        </template>
      </el-table-column>
      <el-table-column prop="keyword" label="关键字" min-width="80"/>
      <el-table-column prop="firstAnswer" label="首次接听" min-width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.firstAnswer === 1" class="ms-success">接听</span>
          <span v-else-if="scope.row.firstAnswer === 2" class="">拒接</span>
          <span v-else-if="scope.row.firstAnswer === 3" class="">拒绝</span>
          <span v-else-if="scope.row.firstAnswer === 4" class="">空错号</span>
          <span v-else-if="scope.row.firstAnswer === 5" class="">无咨询</span>
          <span v-else-if="scope.row.firstAnswer === 6" class="">无人接听</span>
        </template>
      </el-table-column>
      <el-table-column prop="customerName" label="员工" min-width="100"/>

      <el-table-column label="操作" fixed="right" min-width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click.native.prevent="editRow(scope.$index)"> 编辑 </el-button>
          <el-button  type="text" size="small" @click.native.prevent="deleteRow(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="pagination"
      layout="total, sizes, prev, pager, next, jumper"
      :current-page.sync="table.pagination.page"
      :total="table.pagination.totalRow"
      :page-size="table.pagination.pageSize"
      :page-sizes="table.pagination.pageSizes"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>
  </div>
</template>

<script>
  import MsSearch from '@/components/common/Search.vue'
  import { SEARCH_CONDITION, FormArgument } from '@/models/customer/service/service-feedback'
  import MsSlide from '@/components/common/Slide.vue'
  import MsConfirmButton from '@/components/common/ConfirmButton.vue'
  import FormTokenApi from '@/api/system/form-token'
  import Api from '@/api/customer/service/service-feedback'
  import ResponseParse from '@/utils/response-parse'

  export default {
    components: {
      MsSearch,
      MsSlide,
      MsConfirmButton
    },
    data () {
      return {
        search: {
          list: [],
          condition: {}
        },
        table: {
          loading: true,
          list: [],
          pagination: {}
        },
        row: {
          edit: {
            enabled: false,
            index: 0
          },
          form: new FormArgument(),
          format: 'yyyy-MM-dd'
        },
        tbHeight: document.documentElement.clientHeight - 110,
        pickerOptions: {
          disabledDate (time) {
            return time.getTime() > Date.now()
          },
          shortcuts: [{
            text: '今天',
            onClick (picker) {
              picker.$emit('pick', new Date())
            }
          }, {
            text: '昨天',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          }, {
            text: '两天前',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 2)
              picker.$emit('pick', date)
            }
          }, {
            text: '三天前',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 3)
              picker.$emit('pick', date)
            }
          }, {
            text: '四天前',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 4)
              picker.$emit('pick', date)
            }
          }, {
            text: '五天前',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 5)
              picker.$emit('pick', date)
            }
          }]
        }
      }
    },
    mounted: function () {
      this.tbHeight = document.documentElement.clientHeight - 110
    },
    created () {
      this.search.list = SEARCH_CONDITION
      this.table.loading = true
      this.table.list = []
      this.requestList()
    },
    methods: {
      requestList () {
        let params = Object.assign({}, {page: this.table.pagination.page, pageSize: this.table.pagination.pageSize},
          this.search.condition)
        this.table.loading = true
        Api.dailyFeedbackList({search: params}, response => {
          let status = response.status || 0
          let body = response.data || []
          if (status === 200 || status === 204) {
            body.forEach(value => {
              value.day = value.day + ''
            })
            this.table.list = body
            this.table.pagination = ResponseParse.pagination(response.headers)
//            if (this.table.pagination.totalPage === this.table.pagination.page) {
//              this.tbHeight = ''
//            } else {
//              this.$set(this, 'tbHeight', this.PHeigh - this.$refs.msSearch.clientHeight)
//            }
          } else {
//            this.tbHeight = ''
            this.$message.error(body.error || '数据获取失败')
          }
          this.table.loading = false
        })
      },
      updateConditions (conditions) {
        this.search.condition = Object.assign({}, conditions)
        this.requestList()
      },
      handleSizeChange (val) {
        this.table.pagination.pageSize = val
        this.requestList()
      },
      handleCurrentChange (val) {
        this.table.pagination.page = val
        this.requestList()
      },
      addRow () {
        this.row.form = {}
        this.row.edit.enabled = false
        this.row.edit.index = 0
//         获得 form token
        FormTokenApi.create(response => {
          let status = response.status || 0
          let body = response.data || []
          if (status >= 200 && status <= 204) {
            this.row.form.token = body.token || ''
          }
        })

        this.showSlide('slideModifyRow')
      },
      editRow (index) {
        const rows = this.table.list.slice(index, index + 1)

        this.row.form = Object.assign({}, rows[0])
        this.row.edit.enabled = true
        this.row.edit.index = index

        this.showSlide('slideModifyRow')
      },
      submitRow () {
        this.$refs['formModifyRow'].validate((valid) => {
          if (valid) {
            if (this.row.edit.enabled) {
              Api.modify({id: this.row.form.id, form: this.row.form}, response => {
                let status = response.status || 0
                let body = response.data || []
                if (status >= 200 && status <= 204) {
                  let index = this.row.edit.index
                  let data = Object.assign({}, this.table.list[index], body)

                  this.table.list.splice(index, 1, data)

                  this.$message.success('修改成功')

                  // 关闭
                  this.$refs['slideModifyRow'].close()
                } else {
                  this.$message.error(body.error || '修改失败')
                }
              })
            } else {
              Api.create({form: this.row.form}, response => {
                let status = response.status || 0
                let body = response.data || []
                if (status >= 200 && status <= 204) {
                  // 新数据加到数组开头
                  this.table.list.unshift(body)

                  // 提示
                  this.$message.success('新增成功')

                  // 关闭
                  this.$refs['slideModifyRow'].close()
                } else {
                  this.$message.error(body.error || '新增失败')
                }
              })
            }
          } else {
            return false
          }
        })
      },
      deleteRow (index) {
        Api.delete({id: this.table.list[index].id}, response => {
          let status = response.status || 0
          let body = response.data || []
          if (status >= 200 && status <= 204) {
            this.table.list.splice(index, 1)
            this.$message.success('删除成功')
          } else {
            this.$message.error(body.error || '删除失败')
          }
        })
      },
      resetForm (formName) {
        this.$refs[formName].resetFields()
      },
      showSlide (ref) {
        this.$refs[ref].show()
      },
      closeSlideModify () {
        this.row.form = {}
        this.row.edit.enabled = false
        this.row.edit.index = 0
      },
      dataFormat (row, column) {
        const data = row[column.property] + ''
        if (data === '' || data === undefined) {
          return ''
        } else if (data.length === 8) {
          let _data = data.substring(0, 4) + '-' + data.substring(4, 6) + '-' + data.substring(6, 8)
          return _data
        }
      }
    }
  }
</script>
